package pub.wkq.thread;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * 简化的线程池，仅用来说明工作原理
 * @author 王开琦
 */
class MyThreadPool {
    /**
     * 利用阻塞队列实现生产者——消费者模式
     */
    private BlockingQueue<Runnable> workQueue;
    /**
     * 保存内部工作线程
     */
    private List<WorkerThread> threads = new ArrayList<>();

    MyThreadPool(int poolSize, BlockingQueue<Runnable> workQueue) {
        this.workQueue = workQueue;
        //创建工作线程
        for (int idx = 0; idx < poolSize; idx++) {
            WorkerThread thread = new WorkerThread();
            thread.start();
            threads.add(thread);
        }
    }

    //提交任务
   public void execute(Runnable command) {
        workQueue.add(command);
    }

    /**
     * 工作线程负责消费任务，并执行任务
     */
    class WorkerThread extends Thread {
        @Override
        public void run() {
            while (true) {
                Runnable task = null;
                try {
                    task = workQueue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                task.run();
            }
        }
    }
}
